package com.example.his.api.mis.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.example.his.api.common.R;
import com.example.his.api.db.pojo.UserEntity;
import com.example.his.api.mis.controller.form.*;
import com.example.his.api.mis.service.UserService;
import com.example.his.api.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/mis/user")
@Slf4j
public class Usercontroller {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody @Validated LoginForm form){
       Integer userId =  userService.login(form);
       if (Objects.isNull(userId)){
           return R.ok().put("result",false);
       }
        /**
         * 实现多端互斥 先让其他段令牌失效
         */
        StpUtil.logout(userId,"web");
        //再登录
        StpUtil.login(userId,"web");
        //获取token
        String token = StpUtil.getTokenValueByLoginId(userId, "web");
        //获取用户的权限列表
        List<String> permissions = StpUtil.getPermissionList();
        //向前端返回数据
        return R.ok().put("result", true).put("token", token).put("permissions", permissions);
    }

    @GetMapping("/logout")
//    @SaCheckLogin
    public R logout(){
          //重satokn 通过token 获取userid
        int userId = StpUtil.getLoginIdAsInt();
        //退出登录
        StpUtil.logout(userId,"web");
        return R.ok();
    }

    @PostMapping("/updatePassword")
//    @SaCheckLogin
    public R updatePassword(@RequestBody @Validated UpdatePasswordForm form){
        int userId = StpUtil.getLoginIdAsInt();
        form.setUserId(userId);
        Boolean result = userService.updatePassword(form);
        return R.ok().put("result",result);
    }



    @PostMapping("/searchByPage")
    public R searchByPage(@Valid @RequestBody SearchUserByPageForm form) {
        PageUtils pageUtils = userService.searchByPage(form);
        return R.ok().put("page", pageUtils);
    }

    @PostMapping("/insert")
    @Transactional(rollbackFor = Exception.class)
    public R insert(@Valid @RequestBody InsertUserForm form) {
        UserEntity user = BeanUtil.toBean(form, UserEntity.class);
        user.setStatus(1);
        user.setRole(JSONUtil.parseArray(form.getRole()).toString());
        return R.ok().put("result", userService.insert(user));
    }

    @PutMapping("/searchById/{id}")
    public R searchById(@NotNull  @PathVariable("id") Integer id) {
        UserEntity user = userService.searchById(id);
        Map<String, Object> map = BeanUtil.beanToMap(user);
        return R.ok().put("result", map);
    }

    @PostMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public R update(@Valid @RequestBody UpdateUserForm form) {
        UserEntity userEntity = BeanUtil.toBean(form, UserEntity.class);
        userEntity.setId(form.getUserId());
        userEntity.setRole(JSONUtil.parseArray(form.getRole()).toString());
        boolean b = userService.updateById(userEntity);
        if (b) {
            //该用户的Web端、APP端、小程序端等，全部退出登陆
            StpUtil.logout(form.getUserId());
        }
        return R.ok().put("result", b);
    }


    @PostMapping("/deleteByIds")
    public R deleteByIds(@Valid @RequestBody DeleteUserByIdsForm form) {
        Integer userId = StpUtil.getLoginIdAsInt();
        if (form.getIds().contains(userId)) {
            return R.error("您不能删除自己的帐户");
        }
        int rows = userService.deleteByIds(form.getIds());
        if (rows > 0) {
            for (Integer id : form.getIds()) {
                StpUtil.logout(id);
            }
        }
        return R.ok().put("rows", rows);
    }


    @PutMapping("/dismiss/{id}/{status}")
    public R dismiss(@NotNull @PathVariable("id") Integer id,@NotNull @PathVariable("status")Integer status) {
        int rows = userService.dismiss(id,status);
        if (rows > 0 && status == 2) {
            StpUtil.logout(id);
        }
        return R.ok().put("rows", rows);
    }


    @GetMapping("/searchDoctorById")
    public R searchDoctorById() {
        Integer userId = StpUtil.getLoginIdAsInt();
        HashMap map = userService.searchDoctorById(userId);
        return R.ok().put("result", map);
    }
}
